package com.googlecode.restitory.gae.troller;

import java.util.ArrayList;
import java.util.Random;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.RetryOptions;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.googlecode.restitory.gae.Request;
import com.googlecode.restitory.gae.Response;
import com.googlecode.restitory.gae.Type;
import com.googlecode.restitory.gae.hook.AbstractHook;

public class TrollerHook extends AbstractHook {

	private static final int TASKS_PER_TIMER = 100;

	@Override
	public Response handle(Request request) {
		if (request.getPath().equals("/_/troller/post")) {
			JsonObject obj = new JsonObject();
			obj.addProperty("uploadDate", System.currentTimeMillis());
			int i = new Random().nextInt(100000);
			obj.addProperty("number", i);
			obj.addProperty("text", Integer.toString(i));
			Gson gson = new GsonBuilder().create();
			Request req = request.copy().setContent(gson.toJson(obj)).setPath("/troller").setType(Type.POST)
					.setContentType("application/json");
			Response resp = getChain().execute(req);
			return resp.setRequest(request);
		}

		if (request.getPath().equals("/_/troller/queue")) {
			Queue queue = QueueFactory.getQueue("troller");
			ArrayList<TaskOptions> tasks = new ArrayList<TaskOptions>(TASKS_PER_TIMER);
			for (int i = 0; i < TASKS_PER_TIMER; i++) {
				RetryOptions retry = RetryOptions.Builder.withTaskRetryLimit(1);
				tasks.add(TaskOptions.Builder.withUrl("/_/troller/post").method(Method.POST).retryOptions(retry));
			}
			queue.add(tasks);
		}

		return getChain().execute(request);
	}

}
